import {
    URL_ADD_SUBSCRIBER,
    URL_ADD_VIP,
    URL_CHANNEL_LIST,
    URL_CHANNEL_SUBSCRIBER,
    URL_CHECK_TELEGRAM,
    URL_COMPLETE_MISSION,
    URL_DAILY_MISSION,
    URL_ENERGY_FLOW,
    URL_FOLLOW_REWARD,
    URL_GETTOPUSER,
    URL_GET_MAX_ENERGY,
    URL_GET_MISSION,
    URL_GET_REGISTER_ENERGY,
    URL_INVITE,
    URL_INVITEPAGE,
    URL_INVITE_RANK,
    URL_IS_LOGIN,
    URL_LOGIN_OUT,
    URL_LOGS,
    URL_METAMASK,
    URL_MISSION_STATUS,
    URL_PING,
    URL_SIGN,
    URL_SIGN_LIST,
    URL_USERENERGYCOUNT,
    URL_USER_INFO,
    URL_VIP_LIST
} from "@/comm/api";
import { get, post } from "@/comm/request";
import { toast } from "@/components/toast/toast";
import i18n from "@/locals";
import Web3 from "web3"
import detectProvider from '@metamask/detect-provider';
import { defineStore } from "pinia";

const SUCCESS = 200;
interface Res<T> {
    code: number;
    info: string;
    data: T;
}

let tid = 0;
let ping1 = 0;
let ping2 = 0;

interface IState {
    hasRegisterMission: boolean;
    info: any;
    device: any;
    energyList: any[];
    signIn: boolean;
    subscribers: any[];
    subscriberedList: any[];
    thirdUsers: any[];
    vipList: any[];
    missions: any[];
    dailyMissins: any[];
    invites: any[];
    inviteCount: number; //邀请总人数
    inviteEnergy: number; //邀请总能量
    inviteRank: any[]; //邀请榜单
    recommend: string;
    sign: {
        keepSignDays: number;
        missions: any[];
        state: number;
    };
    curSubs: any;
    willComplete: number,
    userEnergyCount: any[],
    energyCount: {
        totalInvites: number,
        totalEnergy: number,
        todayEnergy: number,
        totalLuckEnergy: number,
        todayLuckEnergy: number,
        telegramEnergy: number,
        twitterEnergy: number
    },
    registerEnergy: number,
    registerEnergyMax: number,
    isTelegramUser: boolean,
    energyChange: number;
    inPage: boolean;
    walletLogin: boolean;
    wallet: any;
    isCheckLogin: boolean
}

export const MAP_MISSION: any = {
    REGISTER_COMPLETE: {
        // title: "注冊獎勵",
        title: i18n.global.t("message.MAP_MISSION.a"),
        // desc: "注册...."
        desc: i18n.global.t("message.MAP_MISSION.b")
    },
    VIEW_SMART: {
        // title: "查看聪明钱",
        title: i18n.global.t("message.MAP_MISSION.c"),
        // desc: "查看...."
        desc: i18n.global.t("message.MAP_MISSION.d")
    },
    REGISTER_ACTIVITY_REWARDS: {
        title: i18n.global.t("message.MAP_MISSION.e"),
        // desc: "注册...."
        desc: i18n.global.t("message.MAP_MISSION.f")
    }
    // SIGN_IN: {
    //     title: "簽到",
    //     desc: "簽到........"
    // },
    // INVITE_FIRST_REWARD: {
    //     title: "邀請第1次",
    //     desc: "邀請........"
    // },
    // INVITE_SECOND_REWARD: {
    //     title: "邀請第2次",
    //     desc: "邀請........"
    // },
    // INVITE_THIRD_REWARD: {
    //     title: "邀請第3次",
    //     desc: "邀請........"
    // },
    // INVITE_FOURTH_REWARD: {
    //     title: "邀請第4次",
    //     desc: "邀請........"
    // }
};

export const useUser = defineStore("user", {
    state: (): IState => ({
        hasRegisterMission: false,
        info: null,
        device: null,
        energyList: [],
        signIn: false,
        subscribers: [],
        subscriberedList: [],
        thirdUsers: [],
        vipList: [],
        missions: [],
        dailyMissins: [],
        invites: [],
        inviteCount: 0,
        inviteEnergy: 0,
        inviteRank: [],
        recommend: "",
        sign: {
            keepSignDays: 0,
            missions: [],
            state: 0
        },
        curSubs: {},
        willComplete: 0,
        userEnergyCount: [],
        energyCount: {
            totalInvites: 0,
            totalEnergy: 0,
            todayEnergy: 0,
            totalLuckEnergy: 0,
            todayLuckEnergy: 0,
            telegramEnergy: 0,
            twitterEnergy: 0,
        },
        registerEnergy: 0,
        registerEnergyMax: 0,
        isTelegramUser: false,
        energyChange: 0,
        inPage: true,
        walletLogin: false,
        wallet: {
            nonce: ''
        },
        isCheckLogin: false
    }),
    getters: {
        isLogin(state) {
            return this.isCheckLogin
            // return !!state.info;
        },
        noEmail(state) {
            console.log("email ----- none---")
            if (localStorage.getItem("token")) {
                if (state.info && !state.info.email) {
                    return true;
                }
            }
            return false;
        },
        walletNonce(state){
            return state.wallet?.nonce || ''
        }
    },
    actions: {
        //保存用户nonce
        async setUserWalletNonce(nonce: string) {
            console.log('保存用户nonce', nonce);
            this.wallet.nonce = nonce;
        },
        // metamask登录之后 监听网络切换
        async listenNetwork() {
            const provider: any = await detectProvider();
            provider.on('chainChanged', this.onchangeChain.bind(null, provider));
        },
        // 判断是否以太坊 调起切换网络
        async switchNetwork(networkId: any) {
            // try {
            //     await provider.request({
            //         method: 'wallet_switchEthereumChain',
            //         params: [{ chainId: networkId }],
            //     });
            //     console.log('Network switched successfully');
            // } catch (error) {
            //     console.error('Failed to switch network:', error);
            // }
        },
        // 用户metamask登录之后 监听网络变化
        async onchangeChain(provider: any, chainId: any) {
            let recommendCode = localStorage.getItem("code");

            console.log(chainId, provider);
            // const networkId = await provider.request({ method: 'eth_chainId' });
            // console.log(networkId, "networkId");
            const accounts = await provider.request({ method: 'eth_accounts' });
            const address = accounts[0];
            let netId = "";
            // let netId = Web3.utils.hexToNumberString(chainId)
            // 处理网络改变事件
            console.log('Network changed:', netId);
            let param = {
                address,
                recommendCode,
                netId
            }
            let res: any = await post(URL_METAMASK, param, true)
            if (res.code == 200) {
                localStorage.setItem("token", res.data.token);
            }
            let userInfo = await this.getUserInfo();
        },
        async checkLogin() {
            return localStorage.getItem("token");
            // let res: any = await get(URL_IS_LOGIN);
            // console.log(res, "is login");
            // if (res.code == 200 && res.data) {
            //     return true;
            // }
            // return false;
        },
        async checkUserLogin() {
            let res: any = await get(URL_IS_LOGIN);
            console.log(res, "is login");
            if (res.code == 200 && res.data) {
                this.isCheckLogin = true
                return
            }
            this.isCheckLogin = false
        },
        async getRegisterEnergyMax() {
            let res: any = await get(URL_GET_MAX_ENERGY);
            this.registerEnergyMax = Math.floor(res.data / 100);
        },
        async getRegisterEnergy() {
            let res: any = await post(URL_GET_REGISTER_ENERGY);
            this.registerEnergy = res.data / 100;
            console.log(11111)
            this.getUserInfo();
            localStorage.setItem("willReward", "0");
        },
        async getUserInfo(flag = true) {
            this.checkUserLogin()

            let res: any = await get(URL_USER_INFO).catch(e => {
                console.log("login err", e);
                return {};
            });

            console.log("getUserInfo", res, typeof res);
            if (!res.hasOwnProperty("code")) {
                return "unknown err";
            }
            if (res.code == 200 && res.data?.user) {
                this.info = res.data.user;
                this.hasRegisterMission = res.data.hasRegisterMission;
                this.info.energy = this.info.energy / 100;
                this.device = res.data.userDevice;

                // this.energyList = res.data.energyList || [];
                this.signIn = res.data.signIn;

                this.thirdUsers = res.data.thirdUsers;
                // 判断是否有多个监听
                if ((window as any).ethereum && (window as any).ethereum.isMetaMask) {
                    // const provider: any = await detectProvider();
                    // const isEventListenerRegistered = provider.listenerCount('chainChanged') > 0;
                    // console.log(provider.listenerCount('chainChanged'), "wwww");
                    // if (!isEventListenerRegistered && this.device.loginType == 'METAMASK') {
                    //     this.listenNetwork()
                    // }
                }

                if (flag) {
                    this.getStatus();
                    this.getuserEnergyCount();
                }

                // this.subscribers = res.data.subscribers || [];
                /*
                setTimeout(async () => {
                    this.getMission();
                    this.getClocked();
                    this.getChannelList();
                    this.getEnergyFlow();
                    this.getInvite();
                    this.getDaliyMission();
                    // await this.getVipList();
                    this.getSubscriberList();
                    this.getRankInvite();
                }, 30);
                */
                return null;
            } else if (res.code == 401) {
                localStorage.removeItem("token");
                this.info = null;
            } else if (res.code == 500) {
                localStorage.removeItem("token");
                this.info = null;
            }
            return res.info;
        },
        async getStatus() {
            let res: any = await get(URL_MISSION_STATUS);
            console.log("willComplete ======", res.data);
            this.willComplete = res.data || 0;
            clearTimeout(tid);
            tid = window.setTimeout(() => {
                this.getStatus();
            }, 700000);
        },
        quit() {
            console.log('执行退出操作')
            clearTimeout(tid);
            post(URL_LOGIN_OUT, null, true).then(res => {
                console.warn(res, typeof res);
                this.info = null;
                localStorage.removeItem("walletLogin");
                localStorage.removeItem("token");
                window.location.href = "/"
            });
        },
        changeRecommend(val: any) {
            console.log("推荐码========", val)
            this.recommend = val;
        },
        changeInfo(val: any) {
            this.info = val;
        },
        changeCurSubs(val: any) {
            this.curSubs = val;
        },
        async getMission() {
            get(URL_GET_MISSION, {}).then((res: any) => {
                console.warn(res, "---ww", typeof res);
                this.missions = res.data || [];
                this.missions.forEach(i => (i.energyAmount = i.energyAmount / 100));
            });
        },
        async getClocked() {
            const res: Res<any> = await get(URL_SIGN_LIST, {});
            if (res.code === SUCCESS) {
                this.sign = res.data;
                this.signIn = res.data?.signIn;
                // this.sign.keepSignDays = res.data?.keepSignDays;
                this.sign.missions.forEach(i => (i.energyAmount = i.energyAmount / 100));
                // console.log('yzt签到数据', res);
                return res.data;
            }
        },
        async toSign() {
            let res: any = await get(URL_SIGN, {});
            // console.log('yzt签到是否成功', res);
            if (res.code == 200) {
                // this.info.energy = res.data;
                // this.getUserInfo();
                return null;
            }
            return res.info;
        },
        async completeMission(item: any) {
            let res: any = await post(URL_COMPLETE_MISSION, item, true);
            if (res.code == 200) {
                // this.info.energy = res.data;
                item.isComplete = 1;
                this.getUserInfo();
                return null;
            }
            return res.info;
        },
        async addSubscriber(param: any) {
            let res: any = await post(URL_ADD_SUBSCRIBER, param, true);
            if (res.code == 200) {
                this.getUserInfo();
                return null;
            }
            return res.info;
        },
        async getChannelList() {
            let res: any = await get(URL_CHANNEL_LIST);
            if (res.code == 200) {
                console.log("chanel", res.data);
                this.subscribers = res.data || [];
                this.subscribers.forEach(i => (i.energy = i.energy / 100));
            }
        },
        async getEnergyFlow() {
            let res: any = await post(URL_ENERGY_FLOW, {}, true);
            if (res.code == 200) {
                console.log("energy", res.data);
                this.energyList = res.data.records || [];
                this.energyList.forEach(i => (i.amount = i.amount / 100));
                return this.energyList;
            }
            return [];
        },
        async getEnergyFlowNew(size = 10, number = 1) {
            let res: any = await post(URL_ENERGY_FLOW, { pageSize: size, pageNumber: number }, true);
            if (res.code == 200) {
                return res.data;
            }
            return null;
        },
        async getInvite(size = 10, number = 1) {
            let res: any = await get(URL_INVITE, { pageSize: size, pageNumber: number });
            if (res.code == 200) {
                console.log("invite", res.data);
                // this.energyList = res.data.records || [];
                this.invites = res.data?.users || [];
                this.inviteCount = res.data?.count;
                this.inviteEnergy = res.data?.energyCount / 100;
                this.invites.forEach(i => (i.energy = i.energy / 100));
                return res;
            }
        },
        async addVip(param: any) {
            let res: any = await post(URL_ADD_VIP, param, true);
            if (res.code == 200) {
                // console.log("invite", res.data);
                this.getUserInfo();
                // this.energyList = res.data.records || [];
                // this.invites = res.data;
                return null;
            }
            return res.info;
        },
        async getDaliyMission() {
            let res: any = await get(URL_DAILY_MISSION);
            // console.log("日常任务", res);
            this.dailyMissins = res.data || [];
            this.dailyMissins.forEach(i => (i.energyAmount = i.energyAmount / 100));
        },
        async getVipList() {
            let res: any = await get(URL_VIP_LIST);
            console.log("vip", res);
            this.vipList = res.data || [];
            this.vipList.forEach(i => (i.price = i.price / 100));
            // this.dailyMissins = res.data || [];
        },
        async getSubscriberList() {
            let res: any = await get(URL_CHANNEL_SUBSCRIBER);
            console.log("vip", res);
            this.subscriberedList = res.data || [];
        },
        async getRankInvite(size: number = 10, number = 1) {
            let res: any = await get(URL_INVITE_RANK, { pageSize: size, pageNumber: number });
            console.log("vip", res);
            this.inviteRank = res.data || [];
            if (this.inviteRank.forEach) {
                this.inviteRank.forEach(i => {
                    if (i.inviteRewardEnergy) {
                        return i.inviteRewardEnergy = i.inviteRewardEnergy / 100
                    }
                    return i;
                });
            }
        },
        async getInvitePage(size: number = 10, number = 1) {
            let res: Res<any> = await post(URL_INVITEPAGE, { pageSize: size, pageNumber: number }, true);
            if (res.code === 200) {
                return res.data;
            } else {
                return null;
            }
        },
        async getuserEnergyCount<T>() {
            const res: Res<T> = await get(URL_USERENERGYCOUNT);
            console.log('yzt_能量列表 =====', res);
            if (res.code === SUCCESS) {
                let obj: any = res.data;
                this.energyCount.totalInvites = obj.totalInvites;
                this.energyCount.totalEnergy = obj.totalEnergy * 0.01;
                this.energyCount.todayEnergy = obj.todayEnergy * 0.01;
                this.energyCount.totalLuckEnergy = obj.totalLuckEnergy * 0.01;
                this.energyCount.todayLuckEnergy = obj.todayLuckEnergy * 0.01;
                this.energyCount.telegramEnergy = obj.telegramEnergy * 0.01;
                this.energyCount.twitterEnergy = obj.twitterEnergy * 0.01;
                this.energyChange++;
                return obj;
            }
        },
        async getTopUser<T>(page = 1, size = 10) {
            const res: Res<T> = await get(URL_GETTOPUSER, { pageNumber: page, pageSize: size });
            // console.log('yzt邀请榜单', res);
            if (res.code === SUCCESS) {
                return res.data;
            }
        },
        async getLogs<T>(page = 1, size = 10) {
            const res: Res<T> = await get(URL_LOGS, { pageNumber: page, pageSize: size });
            // console.log('yzt登录日志数据', res);
            return res.data;
        },
        async checkIsTelegramUser(id: any) {
            let res: any = await get(URL_CHECK_TELEGRAM.replace("@", id));
            if (res.data) {
                this.isTelegramUser = true;
            }
        },
        async getJoinNumberReword() {
            // let res: any = await get(URL_FOLLOW_REWARD.replace("@", isTelegram ? "2" : "1"));
            // console.log("get reward", res);
            this.getUserInfo(false);
            // this.getEnergyFlow();
        },
        changeInPage(val: boolean) {
            this.inPage = val;
        },
        ping() {
            clearInterval(ping1);
            clearTimeout(ping2);
            ping1 = window.setInterval(() => { this.sendPing() }, 1 * 60000);
            ping2 = window.setTimeout(() => { this.sendPing() }, 5000);
        },
        sendPing() {
            if (this.info && this.inPage) {
                get(URL_PING, {}, 1);
            }
        }
    }
});
